let ROW_INDEX = 0
let COL_INDEX = 0
let isComplete = false
// wavesurfer的初始化
let wavesurfer = WaveSurfer.create({
    container: document.querySelector('#waveform'),
    waveColor: '#b68160',
    progressColor: '#4fd2c6',
    cursorColor: '#ea8c52',
    barWidth: 2,
    barRadius: 2,
    cursorWidth: 0,
    height: 228,
    barGap: 2,
    partialRender: true,
    pixelRatio: 1,
    plugins: [
        WaveSurfer.cursor.create({
            opacity: 1,
            color: '#ea8c52',
            width: '3px'
        })
    ]});

$(function () {

    initWaveSuffer()

});



layui.use(['element', 'layer', 'upload', 'table'], function () {
    //导航的hover效果、二级菜单等功能，需要依赖element模块
    var element = layui.element;
    var upload = layui.upload;
    var table = layui.table;

    //监听导航点击
    element.on('nav(demo)', function (elem) {
        //console.log(elem)
        layer.msg(elem.text());
    });

    //上传文件
    upload.render({
        elem: '#uploadButton'
        , url: '' //改成您自己的上传接口
        , accept: 'file'
        , exts: 'mp3|m4a|wma|wav'
        , auto: false
        //,multiple: true
        , choose: function (obj, res) {


            var files = obj.pushFile();
//加载层-风格4

//loading层
            var index = layer.load(1, { //icon0-2 加载中,页面显示不同样式
                shade: [0.4, '#000'], //0.4为透明度 ，#000 为颜色
                content: '载入中...',
                success: function (layero) {
                    layero.find('.layui-layer-content').css({
                        'padding-top': '40px',//图标与样式会重合，这样设置可以错开
                        'width': '200px',//文字显示的宽度
                        'color':'#bdcbd8',
                        'font-size': '16px'
                    });
                }
            });


            //预读本地文件，如果是多文件，则会遍历。(不支持ie8/9)
            obj.preview(function (index, file, result) {
                // console.log(index); //得到文件索引
                // console.log(file); //得到文件对象
                // console.log(result); //得到文件base64编码，比如图片
                var path = URL.createObjectURL(file);
                // console.log(file); //得到文件对象
                let $ap1 = $("#ap1")
                $ap1.attr("data-source", path);

                $("#fileName").text(file['name'])

                $("#hidden-layer").css("display","none")
                $("#show-layer").css("display","block")

                wavesurfer.load(path);

            });
        }
    });


    //监听单元格事件
    table.on('tool(dataTable)', function (obj) {
        var data = obj.data;
        ROW_INDEX = textToNumber(data.id) - 1
        if (obj.event === 'setStart') {
            COL_INDEX = 0
            if (COL_INDEX === 0 && (ROW_INDEX === 1 || ROW_INDEX === 2)) {

            } else {
                changeColorFromRowColGetCell(ROW_INDEX, COL_INDEX)
            }

        } else if (obj.event === 'setReady') {
            COL_INDEX = 1
            if (COL_INDEX === 0 && (ROW_INDEX === 1 || ROW_INDEX === 2)) {

            } else {
                changeColorFromRowColGetCell(ROW_INDEX, COL_INDEX)
            }


        } else if (obj.event === 'setEnd') {
            COL_INDEX = 2
            if (COL_INDEX === 0 && (ROW_INDEX === 1 || ROW_INDEX === 2)) {

            } else {
                changeColorFromRowColGetCell(ROW_INDEX, COL_INDEX)
            }

        } else if (obj.event === 'setPause') {
            COL_INDEX = 3
            addPauseFromRowColGetCell(ROW_INDEX, COL_INDEX)
        }
    });


});

// WaveSuffer的初始化
function initWaveSuffer() {
    wavesurfer.on('finish', function () {
        // wavesurfer.pause();
        playAudioBtn()
        // alert("123")
    });

    wavesurfer.on('ready', function () {
        layer.closeAll('loading'); //关闭加载层
        let totalTime = secondToDate(parseInt(wavesurfer.getDuration()))
        $('#total-time').text(totalTime)
    });

    wavesurfer.on('audioprocess', function () {
        let secondsTime = secondToDate(parseInt(wavesurfer.getCurrentTime())
        )
        $('#curr-time').text(secondsTime)
    });

    wavesurfer.on('interaction', function () {
        let pauseIconLayer = $("#pauseIconLayer")
        let txt = pauseIconLayer.css("display")
        let playIconLayer = $("#playIconLayer")
        if (txt == 'none') {

            // let pauseBtn = $("#pauseBtn")
            // pauseBtn.trigger("click")
            // wavesurfer.play()
            pauseBtn.css("display", 'block')
            playBtn.css("display", 'none')
            // alert("wavesurfer.play()")
            document.getElementById("pausebtn").click()
        }
    });
}

//诸如"第一题"转为1
function textToNumber(text) {
    let row = 1
    if (text === '第二题') {
        row = 2
    } else if (text === '第三题') {
        row = 3
    }
    return parseInt(row)
}

//改变颜色
function changeColorFromRowColGetCell(row, col) {
    row = parseInt(row)
    col = parseInt(col)
    let currTime = $(".curr-time:first").text()

    // layer.msg("第" + row + "行，第" + col + "列")

    // $("tr[data-index="+row+"]").css("background-color: #1E9FFF;")

    // console.log($("tr[data-index='0']"))
    let tr = $("tr[data-index=" + row + "]");
    let cell = tr.find(".laytable-cell-1-0-" + (col + 1))

    cell.css("background-color", "#2196f361");
    setTimeout(function () {

        cell.css("background-color", "rgba(255,255,255,0)");
    }, 400);
    cell.text(currTime)
    cell.html(currTime)
    cell.val(currTime)
    return cell

}

//改变颜色
function addPauseFromRowColGetCell(row, col) {
    row = parseInt(row)
    col = parseInt(col)
    let currTime = $(".curr-time:first").text()

    // layer.msg("第" + row + "行，第" + col + "列")

    // $("tr[data-index="+row+"]").css("background-color: #1E9FFF;")

    // console.log($("tr[data-index='0']"))
    let tr = $("tr[data-index=" + row + "]");
    let cell = tr.find(".laytable-cell-1-0-" + (col + 1))

    let pauseIndex = parseInt(cell.text())
    pauseIndex += 1
    cell.text(pauseIndex)
    cell.css("background-color", "#2196f361");
    setTimeout(function () {

        cell.css("background-color", "rgba(255,255,255,0)");
    }, 400);


    return cell

}

//根据行号和列号找到单元格
function fromRowColGetCell(row, col) {

    row = parseInt(row)
    col = parseInt(col)


    // $("tr[data-index="+row+"]").css("background-color: #1E9FFF;")

    // console.log($("tr[data-index='0']"))
    var tr = $("tr[data-index=" + row + "]");
    // tr.find(".laytable-cell-1-0-" + (col + 1)).css("background-color", "#4caf5045");

    return tr.find(".laytable-cell-1-0-" + (col + 1))

}

function test() {
    layer.msg(" ROW_INDEX = " + ROW_INDEX + "\n" +
        "----- COL_INDEX = " + COL_INDEX + "\n" +
        "----- isComplete = " + isComplete + "")
}

//根据行号和列号找到时间
function fromRowColGetCellTime(row, col) {
    let cell = fromRowColGetCell(row, col)
    return cell.text()
}

//计算时间差之间有多少秒
//如 00:32 和 02:16之间相差104秒
function getSecondsBetween(first, second) {
    let ret = '0'
    let firstMin = parseInt(first.substring(0, 2))
    let firstSeconds = parseInt(first.substring(3))

    let secondMin = parseInt(second.substring(0, 2))
    let secondSeconds = parseInt(second.substring(3))

    let totalSeconds = (secondMin - firstMin) * 60 + (secondSeconds - firstSeconds)

    ret = parseInt(totalSeconds)
    return ret
}

function getReport() {
    let firstReady = fromRowColGetCellTime(0, 0)
    let firstStart = fromRowColGetCellTime(0, 1)
    let firstEnd = fromRowColGetCellTime(0, 2)
    let firstPause = fromRowColGetCellTime(0, 3)

    let secondStart = fromRowColGetCellTime(1, 1)
    let secondEnd = fromRowColGetCellTime(1, 2)
    let secondPause = fromRowColGetCellTime(1, 3)

    let thirdStart = fromRowColGetCellTime(2, 1)
    let thirdEnd = fromRowColGetCellTime(2, 2)
    let thirdPause = fromRowColGetCellTime(2, 3)


    let firstReadyTime = getSecondsBetween(firstReady, firstStart)
    let firstAnswerTime = getSecondsBetween(firstStart, firstEnd)

    let secondReadyTime = getSecondsBetween(firstEnd, secondStart)
    let secondAnswerTime = getSecondsBetween(secondStart, secondEnd)

    let thirdReadyTime = getSecondsBetween(secondEnd, thirdStart)
    let thirdAnswerTime = getSecondsBetween(thirdStart, thirdEnd)

    let totalTime = getSecondsBetween(firstReady, thirdEnd)
    let totalAnswerTime = firstAnswerTime + secondAnswerTime + thirdAnswerTime

    let fileName = $('#fileName').text()

    firstReadyTime = MistakeToZero(firstReadyTime)
    firstAnswerTime = MistakeToZero(firstAnswerTime)

    secondReadyTime = MistakeToZero(secondReadyTime)
    secondAnswerTime = MistakeToZero(secondAnswerTime)

    thirdReadyTime = MistakeToZero(thirdReadyTime)
    thirdAnswerTime = MistakeToZero(thirdAnswerTime)

    totalTime = MistakeToZero(totalTime)
    totalAnswerTime = MistakeToZero(totalAnswerTime)

    firstPause = MistakeToZero(firstPause)
    secondPause = MistakeToZero(secondPause)
    thirdPause = MistakeToZero(thirdPause)




    let url = 'page/reportTimerPage.html?'
    url += 'firstReadyTime=' + firstReadyTime
    url += '&firstAnswerTime=' + firstAnswerTime
    url += '&secondReadyTime=' + secondReadyTime
    url += '&secondAnswerTime=' + secondAnswerTime
    url += '&thirdReadyTime=' + thirdReadyTime
    url += '&thirdAnswerTime=' + thirdAnswerTime
    url += '&totalTime=' + totalTime
    url += '&totalAnswerTime=' + totalAnswerTime
    url += '&firstPause=' + parseInt(firstPause)
    url += '&secondPause=' + parseInt(secondPause)
    url += '&thirdPause=' + parseInt(thirdPause)
    url += '&fileName=' + fileName

    layer.open({
        type: 2,
        title: '数据报告页',
        shadeClose: true,
        shade: 0.5,
        area: ['380px', '60%'],
        content: url //iframe的url
    });

}

function resetPause() {
    let tr = $("tr[data-index=" + 0 + "]");
    let cell = tr.find(".laytable-cell-1-0-" + (4))
    cell.text(0)

    tr = $("tr[data-index=" + 1 + "]");
    cell = tr.find(".laytable-cell-1-0-" + (4))
    cell.text(0)

    tr = $("tr[data-index=" + 2 + "]");
    cell = tr.find(".laytable-cell-1-0-" + (4))
    cell.text(0)
}

//错误值：NaN、null和undefined转0
function MistakeToZero(obj) {
    if (!obj){
        obj = 0
    }
    return obj
}

function playAudioBtn() {


    wavesurfer.playPause()
    let pauseBtn = $("#pauseIconLayer")
    let playBtn = $("#playIconLayer")
    let txt = pauseBtn.css("display")
    if (txt == 'block') {
        pauseBtn.css("display", 'none')
        playBtn.css("display", 'block')
    } else {
        pauseBtn.css("display", 'block')
        playBtn.css("display", 'none')
    }
}

// 光标选择后播放
function cursorPlay() {
    wavesurfer.play()
    pauseBtn.css("display", 'none')
    playBtn.css("display", 'block')
}

//秒转时间
function secondToDate(result) {
    var h = Math.floor(result / 3600) < 10 ? '0' + Math.floor(result / 3600) : Math.floor(result / 3600);
    var m = Math.floor((result / 60 % 60)) < 10 ? '0' + Math.floor((result / 60 % 60)) : Math.floor((result / 60 % 60));
    var s = Math.floor((result % 60)) < 10 ? '0' + Math.floor((result % 60)) : Math.floor((result % 60));
    return result = m + ":" + s;
}